<template>
  <view :class="classArr" :style="tempStyle" @click="onClick">
    <IBizRawItem :rawItem="modelData" :content="content" />
  </view>
</template>

<script setup lang="ts">
import { IHtmlItem, IPanelRawItem, ITextItem } from '@ibiz/model-core'
import { computed } from 'vue'
import { useNamespace } from '@/use'
import { PanelRawItemController } from './i-biz-panel-raw-item.controller'

// 定义组件接收的属性
const props = defineProps({
  modelData: {
    type: Object as PropType<IPanelRawItem>,
    required: true,
  },
  controller: {
    type: PanelRawItemController,
    required: true,
  },
})

// 获取命名空间和计算类名数组
const ns = useNamespace('panel-rawitem')
const c = props.controller

// 传入内容
const content: Ref<string | number | undefined> = ref('')

const tempStyle = ref('')

const { rawItem } = props.modelData

if (rawItem && rawItem.cssStyle) {
  tempStyle.value = rawItem.cssStyle
}

// 类名控制
const classArr = computed(() => {
  const { id } = props.modelData
  const result: Array<string | false> = [ns.b(), ns.m(id)]
  result.push(...props.controller.containerClass)
  return result
})

const onClick = (event: MouseEvent) => {
  props.controller.onClick(event)
}

watch(
  () => c.data,
  async (newVal) => {
    if (newVal) {
      const rawItemModel = c.model.rawItem
      if (!rawItemModel) {
        return
      }
      let rawItemContent
      const obj = { ...newVal }
      if (rawItemModel.contentType === 'RAW') {
        rawItemContent = (rawItemModel as ITextItem).caption!
      } else if (rawItemModel.contentType === 'HTML') {
        rawItemContent = (rawItemModel as IHtmlItem).content!
      }
      if (rawItemContent && rawItemModel.templateMode) {
        rawItemContent = await ibiz.util.hbs.render(
          rawItemContent.replace('//n', '\n'),
          Object.assign(obj, { data: { ...newVal } }),
        )
      }
      content.value = rawItemContent
    }
  },
  {
    immediate: true,
  },
)
</script>
<style lang="scss">
@import './i-biz-panel-raw-item';
</style>
